﻿

let obj = JSON.parse(sessionStorage.getItem("obj"));



$(".text-input").val(obj.name)
$("#showImg").attr("src", obj.img)



let Addbtn = document.querySelector(".Addbtn");
let input = document.querySelector(".text-input");
let textarea = document.querySelector(".textarea-input");
let File = document.querySelector(".File-input");
let imgtext = document.querySelector("#imgtext");

File.onchange = function () {

    if (File.value != "") {
        document.getElementById("showImg").src = window.URL.createObjectURL(File.files[0]);
        imgtext.innerHTML = File.value;
    } else {
        document.getElementById("showImg").src = "";
        imgtext.innerHTML = "你还未上传图片";
    }

}

Addbtn.onclick = function () {
    if (input.value != "" && textarea.value != "") {

        if (File.value != "") {

            let name = File.value;

            let hzm = name.substring(name.lastIndexOf('.') + 1);


            if (hzm == "png" || hzm == "jpg") {

                let img = File.files[0];


                var formData = new FormData();




                obj.name = input.value;
                obj.spare = textarea.value,



                    formData.append('img', img);
                formData.append('goods', JSON.stringify(obj));



                $.ajax({
                    url: '/Goods/UpdateGoodType',
                    type: 'POST',
                    dataType: 'json',
                    data: formData,
                    cache: false,
                    traditional: true,
                    contentType: false,
                    processData: false,
                    success: function (data) {


                        if (data.code == 0) {
                            Peng.Show(data.message, { type: 'Success' });

                        } else {
                            Peng.Show(data.message, { type: 'Danger' });

                        }
                        input.focus();

                        input.value = "";
                        textarea.value = "";
                        File.value = "";
                        document.getElementById("showImg").src = "";
                        imgtext.innerHTML = "你还未上传图片";
                    },
                    error: function () {

                    }

                });

            } else {
                Peng.Show("只允许 'png' 和 'jpg' 格式的图片", { type: 'Danger' });

            }

        } else {
            Peng.Show("未上传文件", { type: 'Danger' });
            File.click();
        }
    } else {
        Peng.Show("不能有为空的内容", { type: 'Danger' });
        input.focus();
    }
}